//
//  PHAsset+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import Foundation
import Photos
import MobileCoreServices

public extension PHAsset {
    var fileURL: URL? {
        var url: URL? = nil
        let options = PHImageRequestOptions()
        options.isSynchronous = true
        if self.mediaType == PHAssetMediaType.image {
            PHImageManager.default().requestImageData(for: self, options: options, resultHandler: { (_, _, _, info) in
                url = info?["PHImageFileURLKey"] as? URL
            })
        }
        return url
    }

    var fileExtension: String? {
        if let url = fileURL {
            return url.pathExtension
        }
        return nil
    }

    var mimeType: String {
        if let ext = fileExtension {
            if let UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil) {
                let contentType = UTTypeCopyPreferredTagWithClass(UTI.takeUnretainedValue(), kUTTagClassMIMEType)
                if nil != contentType {
                    return String(contentType!.takeRetainedValue() as NSString)
                }
            }
        }
        return "application/octet-stream"
    }
}
